/*
 * @Descripttion:
 * @Author: voanit
 * @Date: 2022-05-05 14:55:34
 * @LastEditors: voanit
 * @LastEditTime: 2022-05-05 16:06:02
 */
import React from 'react'

class Todo extends React.Component {
  state = {
    list: [
      { id: 1, name: '水浒传' },
      { id: 2, name: '西游记' },
      { id: 3, name: '红楼梦' },
    ],
    val: '',
    disabled: false,
    index: 0,
  }
  handle = (e) => {
    this.setState({
      val: e.target.value,
    })
  }
  addHandle = () => {
    // this.state.list.push({
    //   id: this.state.list.length + 1,
    //   name: this.state.val,
    // })
    // console.log(this.state.list, 888222)
    /* 方法1： */
    // this.state.list.push({
    //   id: this.state.list.length + 1,
    //   name: this.state.val,
    // })
    // this.setState({
    //   list: this.state.list,
    // })
    /* 方法2 */
    this.setState({
      list: [
        ...this.state.list,
        { id: this.state.list.length + 1, name: this.state.val },
      ],
      val: '',
    })
  }

  del = (id) => {
    console.log(id, 66)
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    })
  }
  /* 每一项的编辑按钮 */
  edit = (item, index) => {
    this.setState({
      val: item.name,
      disabled: !this.state.disabled,
      index,
    })
  }
  // 修改的编辑按钮
  editHandle = () => {
    var i = this.state.index
    // eslint-disable-next-line react/no-direct-mutation-state
    this.state.list[i].name = this.state.val
    // 数据更新
    this.setState({
      val: '',
      disabled: !this.state.disabled,
    })
  }
  render() {
    return (
      <div>
        御剑乘风来,除魔天地间!===Todo==={this.state.val}==
        <input type="text" value={this.state.val} onChange={this.handle} />
        ==
        <button disabled={this.state.disabled} onClick={this.addHandle}>
          添加
        </button>
        ==
        <button disabled={!this.state.disabled} onClick={this.editHandle}>
          编辑
        </button>
        <ul>
          {this.state.list.map((item, index) => (
            <li key={item.id}>
              标号：{item.id}===书名：{item.name}====
              <button onClick={() => this.del(item.id)}>删除</button>===
              <button onClick={() => this.edit(item, index)}>编辑</button>
            </li>
          ))}
        </ul>
      </div>
    )
  }
}
export default Todo
